package me.seu.demo.service.mqtt;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;

/**
 * hmac加密工具
 *
 * @author liangfeihu
 * @since 2021/11/4 10:34
 */
public class CryptoUtil {

    public static String hmacMd5(String plainText, String key) throws Exception {
        return hmac(plainText, key, "HmacMD5", "%032x");
    }

    public static String hmacSha1(String plainText, String key) throws Exception {
        return hmac(plainText, key, "HmacSHA1", "%040x");
    }

    public static String hmacSha256(String plainText, String key) throws Exception {
        return hmac(plainText, key, "HmacSHA256", "%064x");
    }

    private static String hmac(String plainText, String key, String algorithm, String format) throws Exception {
        if (plainText == null || key == null) {
            return null;
        }

        byte[] hmacResult = null;

        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        mac.init(secretKeySpec);
        hmacResult = mac.doFinal(plainText.getBytes());
        return String.format(format, new BigInteger(1, hmacResult));
    }

    public static void main(String[] args) throws Exception{
        String plainText = "hello world";
        String key = "123456789087654321";

        System.out.println(hmacMd5(plainText, key));
        System.out.println(hmacSha1(plainText, key));
        System.out.println(hmacSha256(plainText, key));
    }

}
